from datetime import datetime, timedelta
from typing import List, Tuple
from config.kline_settings import MAX_RANGE_MINUTES
from utils.logger import logger

class TimeRangeHandler:
    @staticmethod
    def split_time_range(start_time: datetime, end_time: datetime, granularity: str) -> List[Tuple[datetime, datetime]]:
        """
        将时间范围按照K线粒度拆分成多个子范围
        """
        max_minutes = MAX_RANGE_MINUTES[granularity]
        time_ranges = []
        current_start = start_time

        total_minutes = (end_time - start_time).total_seconds() / 60
        logger.info(f"开始拆分时间范围:\n"
                   f"粒度: {granularity}\n"
                   f"总时间跨度: {total_minutes:.2f}分钟\n"
                   f"单次最大请求: {max_minutes}分钟\n"
                   f"预计需要拆分: {max(1, int((total_minutes + max_minutes - 1) / max_minutes))}次")

        while current_start < end_time:
            current_end = min(
                current_start + timedelta(minutes=max_minutes),
                end_time
            )
            time_ranges.append((current_start, current_end))
            logger.info(f"拆分子区间: {current_start} 至 {current_end} "
                       f"({(current_end - current_start).total_seconds() / 60:.2f}分钟)")
            current_start = current_end

        logger.info(f"时间范围拆分完成，共拆分为{len(time_ranges)}个子区间")
        return time_ranges

    @staticmethod
    def datetime_to_timestamp(dt: datetime) -> int:
        """将datetime转换为毫秒级时间戳"""
        return int(dt.timestamp() * 1000)

    @staticmethod
    def timestamp_to_datetime(ts: int) -> datetime:
        """将毫秒级时间戳转换为datetime"""
        return datetime.fromtimestamp(ts / 1000) 